package ca.uvic.cs.cogz.mapping.ui;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import ca.uvic.cs.cogz.mapping.core.MappingTypeManager;
import ca.uvic.cs.cogz.mapping.core.MappingTypeManager.MappingType;

public class MappingTypeFilterDialog extends JDialog {
	private static final long serialVersionUID = 2876514954801494973L;

	private static final String[] COLUMN_NAMES = new String[] { "Mapping type", "Visible" };

	private JTable mappingTypeTable;

	private MappingTypeManager mappingTypeManager;

	public MappingTypeFilterDialog(Frame owner, MappingTypeManager mappingTypeManager) {
		super(owner, "Mapping type control panel");

		this.mappingTypeManager = mappingTypeManager;

		init();
	}

	private void init() {
		setLayout(new BorderLayout());
		setSize(300, 200);
		setResizable(false);

		add(new JScrollPane(getMappingTypeTable()), BorderLayout.CENTER);

		JButton closeButton = new JButton("Close");
		closeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(closeButton);

		add(buttonPanel, BorderLayout.SOUTH);
	}

	private JTable getMappingTypeTable() {
		if (mappingTypeTable == null) {
			mappingTypeTable = new JTable();
			mappingTypeTable.setModel(new MappingTypeTableModel());
		}

		return mappingTypeTable;
	}

	class MappingTypeTableModel extends AbstractTableModel {
		private static final long serialVersionUID = -9129565733243613901L;

		public MappingTypeTableModel() {}

		public String getColumnName(int col) {
			return COLUMN_NAMES[col];
		}

		public int getColumnCount() {
			return COLUMN_NAMES.length;
		}

		public int getRowCount() {
			return MappingType.values().length;
		}

		@SuppressWarnings("unchecked")
		public Class getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}

		public boolean isCellEditable(int row, int col) {
			if (col > 0) {
				return true;
			}
			return false;
		}

		public void setValueAt(Object value, int row, int col) {
			mappingTypeManager.setVisible((MappingType) getValueAt(row, 0), Boolean.parseBoolean(value.toString()));
		}

		public Object getValueAt(int rowIndex, int columnIndex) {
			MappingType mappingType = MappingType.values()[rowIndex];

			if (columnIndex == 0) {
				return mappingType;
			}

			return mappingTypeManager.isVisible(mappingType);
		}
	}
}
